package com.ray.business.api;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ray.base.api.MaterialModelApi;
import com.ray.base.check.CustomerCheck;
import com.ray.base.service.BaseCustomerService;
import com.ray.base.service.BaseTechnologyService;
import com.ray.base.service.compose.GoodsService;
import com.ray.base.service.compose.TechnologyService;
import com.ray.base.table.dto.MaterialModelQueryDTO;
import com.ray.base.table.entity.BaseCustomer;
import com.ray.base.table.entity.BaseMaterialModel;
import com.ray.base.table.entity.BaseTechnologyRecord;
import com.ray.base.table.params.material.model.MaterialModelQueryParams;
import com.ray.base.table.vo.material.model.MaterialModelVO;
import com.ray.business.builder.BusinessGoodsVOBuilder;
import com.ray.business.builder.PurchaseBuilder;
import com.ray.business.builder.PurchaseGoodsBuilder;
import com.ray.business.builder.PurchaseRecordBuilder;
import com.ray.business.check.OrderStepCheck;
import com.ray.business.check.PurchaseCheck;
import com.ray.business.enums.PurchaseStatusEnum;
import com.ray.business.service.*;
import com.ray.business.table.dto.PurchaseInQueryDTO;
import com.ray.business.table.dto.PurchaseQueryDTO;
import com.ray.business.table.entity.*;
import com.ray.business.table.params.business.BusinessQueryParams;
import com.ray.business.table.params.purchase.PurchaseCreateParams;
import com.ray.business.table.params.purchase.PurchaseEditParams;
import com.ray.business.table.params.purchase.PurchaseGoodsPriceParams;
import com.ray.business.table.params.purchase.PurchaseQueryParams;
import com.ray.business.table.vo.BusinessGoodsVO;
import com.ray.business.table.vo.PurchaseGoodsVO;
import com.ray.business.table.vo.PurchaseVO;
import com.ray.common.SysMsgCodeConstant;
import com.ray.common.check.AbstractCheck;
import com.ray.system.builder.CommonPageBuilder;
import com.ray.system.enums.FileTypeEnum;
import com.ray.system.service.SysFileService;
import com.ray.system.table.entity.SysFile;
import com.ray.util.FileRecordUtil;
import com.ray.validate.support.utils.ValidateUtil;
import com.ray.wms.builder.GoodsBuilder;
import com.ray.wms.service.WmsWarehouseService;
import com.ray.wms.service.compose.InService;
import com.ray.wms.table.dto.GoodsDTO;
import com.ray.wms.table.dto.OrderCreateDTO;
import com.ray.wms.table.entity.WmsWarehouse;
import com.ray.woodencreate.beans.LoginUser;
import com.ray.woodencreate.config.SysFileConfig;
import com.ray.woodencreate.exception.BusinessExceptionFactory;
import com.ray.woodencreate.page.CommonPage;
import com.ray.woodencreate.result.MsgCodeConstant;
import com.ray.woodencreate.result.Result;
import com.ray.woodencreate.result.ResultFactory;
import com.ray.woodencreate.util.Assert;
import com.ray.woodencreate.util.LogInUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bo shen
 * @Description: 采购相关接口
 * @Class: PurchaseApi
 * @Package com.ray.business.api
 * @date 2020/6/7 17:52
 * @company <p>Ray快速开发平台</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Service
@Slf4j
public class PurchaseApi {

    @Autowired
    private ProdPurchaseService prodPurchaseService;
    @Autowired
    private ProdPurchaseRecordService prodPurchaseRecordService;
    @Autowired
    private BaseCustomerService baseCustomerService;
    @Autowired
    private WmsWarehouseService wmsWarehouseService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ProdPurchaseBackService prodPurchaseBackService;
    @Autowired
    private ProdPurchaseBackRecordService prodPurchaseBackRecordService;
    @Autowired
    private MaterialModelApi materialModelApi;
    @Autowired
    private ProdOrderGoodsService prodOrderGoodsService;
    @Autowired
    private TechnologyService technologyService;
    @Autowired
    private ProdPurchaseInService prodPurchaseInService;
    @Autowired
    private ProdPurchaseInRecordService prodPurchaseInRecordService;
    @Autowired
    private SysFileService sysFileService;
    @Autowired
    private SysFileConfig sysFileConfig;


    /**
     * 查询采购订单列表信息 分页  非删除的
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<PurchaseVO>> pagePurchases(CommonPage<PurchaseQueryParams, Page<PurchaseVO>> queryParams) {
        Assert.notNull(queryParams, SysMsgCodeConstant.Error.ERR10000001);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        Map<String, WmsWarehouse> wmsWarehouseMap = new HashMap<>();
        Map<String, BaseCustomer> baseCustomerMap = new HashMap<>();
        //查询入库时间对应的采购单
        if(ObjectUtil.isNotNull(queryParams.getEntity().getOutSendStartTime())
                && ObjectUtil.isNotNull(queryParams.getEntity().getOutSendEndTime())){
            PurchaseInQueryDTO purchaseInQueryParams = new PurchaseInQueryDTO();
            purchaseInQueryParams.setOutSendStartTime(queryParams.getEntity().getOutSendStartTime());
            purchaseInQueryParams.setOutSendEndTime(queryParams.getEntity().getOutSendEndTime());
            List<String> orderNos = prodPurchaseInService.list(purchaseInQueryParams,loginUser).stream()
                    .map(ProdPurchaseIn::getOrderNo).collect(Collectors.toList());
            if(ObjectUtil.isEmpty(orderNos)){
                return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, queryParams.getPage());
            }
            queryParams.getEntity().setOrderNos(orderNos);
        }

        CommonPageBuilder<PurchaseQueryDTO, ProdPurchase> commonPageBuilder = new CommonPageBuilder<>(PurchaseQueryDTO.class);
        commonPageBuilder.appendEntity(queryParams.getEntity()).appendQuery(queryParams.getQuery()).appendPage(queryParams.getPage());

        IPage<ProdPurchase> page = prodPurchaseService.page(commonPageBuilder.bulid(), loginUser);
        List<ProdPurchase> orders = page.getRecords();
        //结果对象
        IPage<PurchaseVO> pageList = new Page<>();
        pageList.setTotal(page.getTotal());
        pageList.setCurrent(page.getCurrent());
        pageList.setSize(page.getSize());
        //查询到结果 数据转换
        if (ObjectUtil.isNotNull(orders)) {
            pageList.setRecords(orders.stream().map(sysPurchase -> {
                PurchaseVO orderVO = new PurchaseVO();
                BeanUtil.copyProperties(sysPurchase, orderVO);
                //查询客信息
                BaseCustomer baseCustomer = baseCustomerMap.get(sysPurchase.getCustomerCode());
                if (ObjectUtil.isEmpty(baseCustomer)) {
                    baseCustomer = baseCustomerService.queryCustomerByCustomerCode(sysPurchase.getCustomerCode(), loginUser);
                    baseCustomerMap.put(sysPurchase.getCustomerCode(), baseCustomer);
                }
                orderVO.setCustomerName(baseCustomer.getCustomerName());
                //查询仓库信息
                WmsWarehouse wmsWarehouse = wmsWarehouseMap.get(sysPurchase.getWarehouseCode());
                if (ObjectUtil.isEmpty(wmsWarehouse)) {
                    wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(sysPurchase.getWarehouseCode(), loginUser);
                    wmsWarehouseMap.put(wmsWarehouse.getWarehouseCode(), wmsWarehouse);
                }
                orderVO.setWarehouseName(wmsWarehouse.getWarehouseName());
                return orderVO;
            }).collect(Collectors.toList()));
        } else {
            pageList.setRecords(new ArrayList<>());
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
    }


    /**
     * 创建订单
     *
     * @param createParams 创建对象
     * @return Result
     */
    @Transactional
    public Result<String> createOrder(PurchaseCreateParams createParams) {
        ValidateUtil.validate(createParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        //查询客户数据
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(createParams.getCustomerCode(), loginUser);
        new CustomerCheck(baseCustomer).checkNull("客户不存在");
        PurchaseBuilder orderBuilder = new PurchaseBuilder();
        orderBuilder.append(createParams).appendStatus(PurchaseStatusEnum.UN_CHECK.getValue()).appendCreate(loginUser);

        //保存商品信息
        List<String> keys = new ArrayList<>();
        final List<BigDecimal> quantity = new ArrayList<>();
        List<ProdPurchaseRecord> records = createParams.getGoods().stream().map(purchaseGoodsParams -> {
            if (keys.contains(purchaseGoodsParams.getKey())) {
                log.info("存在相同的物料:{}", purchaseGoodsParams.getKey());
                throw BusinessExceptionFactory.newException("存在相同的物料");
            }
            //采购订单数量
            quantity.add(purchaseGoodsParams.getQuantity());
            keys.add(purchaseGoodsParams.getKey());
            return new PurchaseRecordBuilder().append(purchaseGoodsParams).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());

        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(new BigDecimal(0));
        //保存订单信息
        if (!prodPurchaseService.save(orderBuilder.bulid())) {
            log.info("保存订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("保存订单异常");
        }
        //保存数据
        prodPurchaseRecordService.saveBatch(records);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(), FileTypeEnum.PURCHASE, FileRecordUtil.toFileDTO(createParams.getFiles()), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }

    /**
     * 编辑订单
     *
     * @param editParams 编辑对象
     * @return Result
     */
    @Transactional
    public Result<String> editOrder(PurchaseEditParams editParams) {
        ValidateUtil.validate(editParams);
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(editParams.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购订单不存在").checkCanEdit("订单不能编辑");
        //查询客户数据
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(editParams.getCustomerCode(), loginUser);
        new CustomerCheck(baseCustomer).checkNull("客户不存在");
        PurchaseBuilder orderBuilder = new PurchaseBuilder();
        orderBuilder.append(editParams).appendEdit(loginUser).open().appendStatus(PurchaseStatusEnum.UN_CHECK.getValue());
        //删除数据
        prodPurchaseRecordService.deleteOrderGoods(editParams.getOrderNo(), loginUser);
        //保存商品信息
        List<String> keys = new ArrayList<>();
        final List<BigDecimal> quantity = new ArrayList<>();
        List<ProdPurchaseRecord> records = editParams.getGoods().stream().map(purchaseGoodsParams -> {
            if (keys.contains(purchaseGoodsParams.getKey())) {
                log.info("存在相同的物料:{}", purchaseGoodsParams.getKey());
                throw BusinessExceptionFactory.newException("存在相同的物料");
            }
            keys.add(purchaseGoodsParams.getKey());
            //采购订单数量
            quantity.add(purchaseGoodsParams.getQuantity());
            return new PurchaseRecordBuilder().append(purchaseGoodsParams).appendCode(orderBuilder.getCode()).appendCreate(loginUser).bulid();
        }).collect(Collectors.toList());
        //保存总数
        orderBuilder.append(quantity.stream().reduce(BigDecimal::add).get());
        //保存总价
        orderBuilder.appendTotal(new BigDecimal(0));
        if (!prodPurchaseService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("编辑订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("编辑订单异常");
        }
        //保存数据
        prodPurchaseRecordService.saveBatch(records);
        //删除文件
        sysFileService.deleteFile(orderBuilder.getCode(), FileTypeEnum.PURCHASE.getValue(), loginUser);
        //保存文件
        sysFileService.saveFile(orderBuilder.getCode(), FileTypeEnum.PURCHASE, FileRecordUtil.toFileDTO(editParams.getFiles()), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderBuilder.getCode());
    }


    /**
     * 审核通过
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> passOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(orderNo, loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购订单不存在").checkCanCheck("订单已审核");
        PurchaseBuilder orderBuilder = new PurchaseBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(PurchaseStatusEnum.CHECKED.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodPurchaseService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("通过订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("通过订单异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }

    /**
     * 删除
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> deleteOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(orderNo, loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购单不存在").checkCanCheck("采购单不允许删除");
        PurchaseBuilder orderBuilder = new PurchaseBuilder();
        orderBuilder.appendCode(orderNo).appendEdit(loginUser).delete();
        //编辑订单信息
        if (!prodPurchaseService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("删除订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("删除订单异常");
        }
        //删除数据
        prodPurchaseRecordService.deleteOrderGoods(orderNo, loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }


    /**
     * 取消
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> cancelOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(orderNo, loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购单不存在").checkCanCancel("订单不能取消");
        PurchaseBuilder orderBuilder = new PurchaseBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(PurchaseStatusEnum.CANCEL.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodPurchaseService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("取消订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("取消订单异常");
        }

        //判断退回单是否已取消
        int count = prodPurchaseBackService.countBack(orderNo, loginUser);
        if (count > 0) {
            log.info("存在没有取消的退货单,数量:{}", count);
            throw BusinessExceptionFactory.newException("存在没有取消的退货单");
        }
        //判断入库单是否取消
        int inCount = prodPurchaseInService.countIn(orderNo, loginUser);
        if (inCount > 0) {
            log.info("存在没有取消的入库单,数量:{}", count);
            throw BusinessExceptionFactory.newException("存在没有取消的入库单");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }


    /**
     * 完成订单
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> finishOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(orderNo, loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购订单不存在").checkCanFinish("订单未审核或已完成");
        PurchaseBuilder orderBuilder = new PurchaseBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(PurchaseStatusEnum.FINISH.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodPurchaseService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("通过订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("通过订单异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }


    /**
     * 开启订单
     *
     * @param orderNo
     * @return
     */
    @Transactional
    public Result<String> openOrder(String orderNo) {
        //当前登录对象
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(orderNo, loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购订单不存在").checkCanOpen("订单未完成或已对账");
        PurchaseBuilder orderBuilder = new PurchaseBuilder();
        orderBuilder.appendCode(orderNo).appendStatus(PurchaseStatusEnum.CHECKED.getValue()).appendEdit(loginUser);
        //编辑订单信息
        if (!prodPurchaseService.edit(orderBuilder.bulid(), loginUser)) {
            log.info("开启订单接口异常,参数:{}", JSON.toJSONString(orderBuilder.bulid()));
            throw BusinessExceptionFactory.newException("开启订单异常");
        }
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, orderNo);
    }

    /**
     * 订单详情
     *
     * @param orderNo
     * @return
     */
    public Result<PurchaseVO> viewOrder(String orderNo) {
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(orderNo, loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购单不存在");
        PurchaseVO purchaseVO = new PurchaseVO();
        BeanUtil.copyProperties(prodPurchase, purchaseVO);
        //查询客信息
        BaseCustomer baseCustomer = baseCustomerService.queryCustomerByCustomerCode(prodPurchase.getCustomerCode(), loginUser);
        if (ObjectUtil.isNotNull(baseCustomer)) {
            purchaseVO.setCustomerName(baseCustomer.getCustomerName());
        }
        //查询仓库信息
        WmsWarehouse wmsWarehouse = wmsWarehouseService.queryWarehouseByWarehouseCode(prodPurchase.getWarehouseCode(), loginUser);
        if (ObjectUtil.isNotNull(wmsWarehouse)) {
            purchaseVO.setWarehouseName(wmsWarehouse.getWarehouseName());
        }
        //查询
        List<ProdPurchaseRecord> prodPurchaseRecords = prodPurchaseRecordService.list(orderNo, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();

        List<PurchaseGoodsVO> purchaseGoodsVOS = prodPurchaseRecords.stream().map(prodPurchaseRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodPurchaseRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodPurchaseRecord.getGoodsCode(), loginUser);
                modelMap.put(prodPurchaseRecord.getGoodsCode(), materialModelVO);
            }
            return new PurchaseGoodsBuilder().append(prodPurchaseRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        purchaseVO.setGoods(purchaseGoodsVOS);
        //查询图片信息
        List<SysFile> files = sysFileService.queryFiles(orderNo, FileTypeEnum.PURCHASE.getValue(), loginUser);
        purchaseVO.setFiles(FileRecordUtil.toFileVO(files, sysFileConfig));
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, purchaseVO);
    }


    /**
     * 查询订单可以采购的商品
     *
     * @param queryParams
     * @return
     */
    public Result<IPage<MaterialModelVO>> listInGoods(CommonPage<MaterialModelQueryParams, Page<MaterialModelVO>> queryParams) {
        Assert.notNull(queryParams, "参数[purchaseQueryParams]不能为空");
        LoginUser loginUser = LogInUserUtil.get();
        Page<MaterialModelVO> page = queryParams.getPage();
        if (ObjectUtil.isNotNull(queryParams.getEntity()) && StrUtil.isNotBlank(queryParams.getEntity().getBusinessOrderNo())) {
            //查询订单的商品
            List<ProdOrderGoods> orderGoods = prodOrderGoodsService.list(queryParams.getEntity().getBusinessOrderNo(), loginUser);
            //查询订单对应的采购单
            List<String> orderNos = prodPurchaseService.listByBusinessOrderNo(queryParams.getEntity().getBusinessOrderNo(), loginUser).stream().map(prodPurchase -> {
                return prodPurchase.getOrderNo();
            }).collect(Collectors.toList());
            Map<String, MaterialModelVO> modelVOMap = new HashMap<>();
            //查询订单商品对应的工艺对象
            orderGoods.forEach(prodOrderGoods -> {
                List<BaseTechnologyRecord> baseTechnologyRecords = technologyService.queryTechnologyRecordByModelCode(prodOrderGoods.getGoodsCode(), loginUser);
                log.info("物品:{},订单数量:{}", prodOrderGoods.getGoodsCode(), prodOrderGoods.getQuantity());
                baseTechnologyRecords.forEach(baseTechnologyRecord -> {
                    MaterialModelVO materialModelVO = goodsService.queryGoodsByCode(baseTechnologyRecord.getModelCode(), loginUser);
                    materialModelVO.setUnit(baseTechnologyRecord.getUnit());
                    //分组求和
                    MaterialModelVO newModel = modelVOMap.get(materialModelVO.getKey());
                    if (ObjectUtil.isNull(newModel)) {
                        newModel = materialModelVO;
                        //查询已采购数量
                        BigDecimal purchaseQuantity = prodPurchaseRecordService.countPurchaseQuantity(orderNos, baseTechnologyRecord.getModelCode(), baseTechnologyRecord.getUnit(), loginUser);
                        newModel.setFinishQuantity(NumberUtil.null2Zero(purchaseQuantity));
                    }
                    newModel.setQuantity(NumberUtil.null2Zero(newModel.getQuantity()).add(prodOrderGoods.getQuantity().multiply(baseTechnologyRecord.getUseQuantity())));
                    //已经采购数量
                    modelVOMap.put(newModel.getKey(), newModel);
                });
            });
            List<MaterialModelVO> list = new ArrayList<>(modelVOMap.values());
            //结果对象
            IPage<MaterialModelVO> pageList = new Page<>();
            pageList.setTotal(page.getTotal());
            pageList.setCurrent(page.getCurrent());
            pageList.setSize(list.size());
            pageList.setRecords(list);
            return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000002, pageList);
        } else {
            return materialModelApi.pageMaterialModels(queryParams);
        }
    }

    /**
     * 修改商品单价
     *
     * @param priceParams
     * @return
     */
    public Result<String> editPrice(PurchaseGoodsPriceParams priceParams) {
        LoginUser loginUser = LogInUserUtil.get();
        ProdPurchaseRecord prodPurchaseRecord = prodPurchaseRecordService.queryPurchaseGoods(priceParams.getCode(), loginUser);
        new AbstractCheck<>(prodPurchaseRecord).checkNull("采购商品不存在");
        //查询采购单
        ProdPurchase prodPurchase = prodPurchaseService.queryPurchaseByPurchaseCode(prodPurchaseRecord.getOrderNo(), loginUser);
        new PurchaseCheck(prodPurchase).checkNull("采购单不存在").canDeleteDeduction("采购单已对账");
        BigDecimal diffPrice = priceParams.getPrice().subtract(prodPurchaseRecord.getPrice());
        log.info("价格差:{}", diffPrice);
        final List<BigDecimal> diffPrices = new ArrayList<>();
        //查询所有入库单
        prodPurchaseInRecordService.list(prodPurchaseRecord.getOrderNo(), prodPurchaseRecord.getGoodsCode(), loginUser).forEach(prodPurchaseInRecord -> {
            //修改单价
            prodPurchaseInRecordService.updatePrice(prodPurchaseInRecord.getId(), priceParams.getPrice(), loginUser);
            //计算价格差
            BigDecimal diffTotal = diffPrice.multiply(prodPurchaseInRecord.getQuantity());
            log.info("入库单{},价格差:{}", prodPurchaseInRecord.getInCode(), diffTotal);
            diffPrices.add(diffTotal);
            //修改入库单的总价
            ProdPurchaseIn prodPurchaseIn = prodPurchaseInService.queryPurchaseInByInCode(prodPurchaseInRecord.getInCode(), loginUser);
            new AbstractCheck<>(prodPurchaseIn).checkNull("入库单不存在");
            prodPurchaseInService.updateTotalAmount(prodPurchaseIn.getId(), NumberUtil.null2Zero(prodPurchaseIn.getTotalAmount()).add(diffTotal), loginUser);
        });
        //查询所有退回单
        //查询所有入库单
        prodPurchaseBackRecordService.list(prodPurchaseRecord.getOrderNo(), prodPurchaseRecord.getGoodsCode(), loginUser).forEach(prodPurchaseInRecord -> {
            //修改单价
            prodPurchaseBackRecordService.updatePrice(prodPurchaseInRecord.getId(), priceParams.getPrice(), loginUser);
            //计算价格差
            BigDecimal diffTotal = diffPrice.multiply(prodPurchaseInRecord.getQuantity());
            log.info("退货单{},价格差:{}", prodPurchaseInRecord.getBackCode(), diffTotal);
            diffPrices.add(diffTotal);
            //修改入库单的总价
            ProdPurchaseBack prodPurchaseBack = prodPurchaseBackService.queryPurchaseBackByPurchaseBackCode(prodPurchaseInRecord.getBackCode(), loginUser);
            new AbstractCheck<>(prodPurchaseBack).checkNull("退货单不存在");
            prodPurchaseBackService.updateTotalAmount(prodPurchaseBack.getId(), NumberUtil.null2Zero(prodPurchaseBack.getTotalAmount()).add(diffTotal), loginUser);
        });
        //更新订单总价格
        BigDecimal total = diffPrices.stream().reduce(BigDecimal::add).get();
        log.info("变更总价:{}", total);
        //修改单价
        prodPurchaseRecordService.updatePrice(prodPurchaseRecord.getId(), priceParams.getPrice(), loginUser);
        prodPurchaseService.updateTotalAmount(prodPurchase.getId(), NumberUtil.null2Zero(prodPurchase.getTotalAmount()).add(total), loginUser);
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, priceParams.getCode());
    }

    public Result<List<PurchaseGoodsVO>> goodsList(String orderNo) {
        LoginUser loginUser = LogInUserUtil.get();
        //查询
        List<ProdPurchaseRecord> prodPurchaseRecords = prodPurchaseRecordService.list(orderNo, loginUser);
        Map<String, MaterialModelVO> modelMap = new HashMap<>();

        List<PurchaseGoodsVO> purchaseGoodsVOS = prodPurchaseRecords.stream().map(prodPurchaseRecord -> {
            MaterialModelVO materialModelVO = modelMap.get(prodPurchaseRecord.getGoodsCode());
            if (ObjectUtil.isNull(materialModelVO)) {
                materialModelVO = goodsService.queryGoodsByCode(prodPurchaseRecord.getGoodsCode(), loginUser);
                modelMap.put(prodPurchaseRecord.getGoodsCode(), materialModelVO);
            }
            return new PurchaseGoodsBuilder().append(prodPurchaseRecord).append(materialModelVO).bulid();
        }).collect(Collectors.toList());
        return ResultFactory.createSuccessResult(MsgCodeConstant.Success.SUC00000001, purchaseGoodsVOS);

    }
}
